package com.zoweunion.mechanic.controller.iot;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zoweunion.mechanic.controller.BaseController;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.service.iot.AppManagementService;
import com.zoweunion.mechanic.util.MyException;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.upload.UploadFile;
import com.zoweunion.mechanic.util.upload.UploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/appManagement")
public class AppManagementController extends BaseController {

    @Autowired
    private AppManagementService appManagementService;

    @PostMapping("/banner/pictureList")
    public ResponseBean pictureList(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "轮播图设置_列表展示");
        Map<String, Object> reqMap = JSONObject.parseObject(str, new TypeReference<Map<String, Object>>() {});
        Map<String, Object> resultMap = appManagementService.pictureList(getCurrentUser(request), reqMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
    }


    /**
     * 轮播图设置_详情列表展示
     *
     * @param str
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/banner/pictureDetailList")
    public ResponseBean pictureDetailList(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "轮播图设置_详情列表展示");
        Map<String, Object> reqMap = JSONObject.parseObject(str, new TypeReference<Map<String, Object>>() {});
        Map<String, Object> resultMap = appManagementService.pictureDetailList(getCurrentUser(request), reqMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
    }


    /**
     * 轮播图设置_查询内部链接列表
     *
     * @param str
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/banner/getInnerHrefPath")
    public ResponseBean getInnerHrefPath(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(this.logger, "轮播图设置_查询内部链接列表");
        Map<String, Object> reqMap = JSONObject.parseObject(str, new TypeReference<Map<String, Object>>() {});
        List<Map<String, Object>> result = appManagementService.getInnerHrefPath(reqMap, getCurrentUser(request));
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", result);
    }

    /**
     * 轮播图设置_获取服务商和游客的列表
     *
     * @param str
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/banner/serverAndTourist")
    public ResponseBean serverList(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "轮播图设置_轮播图设置_获取服务商和游客的列表");
        Map<String, Object> reqMap = JSONObject.parseObject(str, new TypeReference<Map<String, Object>>() {});
        List<Map<String, Object>> resultList = appManagementService.serverAndTourist(getCurrentUser(request), reqMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultList);
    }


    /**
     * 轮播图设置_新增图片
     *
     * @param str
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/banner/insertPicture")
    public ResponseBean insertPicture(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(this.logger, "轮播图设置_新增");
        Map<String, Object> reqMap = JSONObject.parseObject(str, new TypeReference<Map<String, Object>>() {});
        User currentUser = this.getCurrentUser(request);
        int result = appManagementService.insertPicture(reqMap, currentUser);
        logAfter(logger);
        if (result > 0) {
            return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", result);
        } else {
            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", result);
        }
    }

    /**
     * 轮播图设置_删除
     *
     * @param str
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/banner/deletePicture")
    public ResponseBean deletePicture(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(this.logger, "轮播图设置_删除");
        Map<String, Object> reqMap = JSONObject.parseObject(str, new TypeReference<Map<String, Object>>() {});
        reqMap.put("update_user", this.getCurrentUser(request).getId());
        int result = appManagementService.deletePicture(reqMap);
        logAfter(logger);
        if (result > 0) {
            return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", result);
        } else if (result == -1) {
            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "游客默认图片不能删除", result);
        } else {
            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", result);
        }
    }

    /**
     * 轮播图设置_更新轮播图
     *
     * @param str
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/banner/updatePicture")
    public ResponseBean updatePicture(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(this.logger, "轮播图设置_修改");
        Map<String, Object> reqMap = JSONObject.parseObject(str, new TypeReference<Map<String, Object>>() {});
        int result = appManagementService.updatePicture(reqMap, this.getCurrentUser(request));
        logAfter(logger);
        if (result > 0) {
            return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", result);
        } else {
            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", result);
        }
    }

    /**
     * 根据主机厂、子服务商或服务商的主键ID(s_id)获取子服务商的列表或自身服务商的信息(用于轮播图功能页面)
     *
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/banner/getSeverListForRotationChart")
    public ResponseBean getSeverListForRotationChart(@RequestBody Map<String,Object> reqMap, HttpServletRequest request) throws MyException {
        logBefore(logger, "轮播图-服务商的列表信息(用于轮播图功能页面)");
        List<Map<String, Object>> serverList = appManagementService.getSeverListForRotationChart(reqMap);
        Map<String,Object> resultMap = new HashMap<>();
        List<Map<String, Object>> newServerList = new ArrayList<>();
        Map<String, Object> settingOfMainEngineServer = new HashMap<>();
        for (Map<String, Object> currentMap: serverList) {
            int server_type = Integer.parseInt(currentMap.get("server_type").toString());
            if(server_type == 1) { // 如果是主机厂，需要从list里面过滤掉，获取主机厂轮播图配置后放到其他返回值里面
                settingOfMainEngineServer.put("server_type", currentMap.get("server_type"));
                settingOfMainEngineServer.put("picture_num", currentMap.get("picture_num"));
                settingOfMainEngineServer.put("is_head", currentMap.get("is_head"));
                settingOfMainEngineServer.put("is_mid", currentMap.get("is_mid"));
            } else {
                newServerList.add(currentMap);
            }
        }
        resultMap.put("serverList", newServerList);
        resultMap.put("setting", settingOfMainEngineServer);
        logAfter(logger);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
    }

    /**
     * 轮播图列表信息(根据主机厂、子服务商或服务商的主键ID(s_id)获取轮播的列表信息)和当前服务商设置的图片和可以上传的数量
     *
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/banner/getRotationChartDataList")
    public ResponseBean getRotationChartDataList(@RequestBody Map<String,Object> reqMap, HttpServletRequest request) throws MyException {
        logBefore(logger, "轮播图-轮播图列表信息");
        Map<String,Object> resultMap = new HashMap<>();
        List<Map<String, Object>> listForShow = appManagementService.getRotationChartDataList(reqMap);
        Map<String,Object> settingMap = appManagementService.getRotationChartSettingForServer(reqMap);

        if(settingMap.get("picture_num") == null) {
            reqMap.put("limit", 0);
        } else {
            reqMap.put("limit", settingMap.get("picture_num"));
        }

        reqMap.put("type", "0");
        List<Map<String, Object>> listForServer = appManagementService.getRotationChartDataListForServer(reqMap);
        Map<String,Object> settingMapForParent = appManagementService.getRotationChartSettingForParentServer(reqMap);

        resultMap.put("listForShow", listForShow);
        resultMap.put("listForServer", listForServer);
        resultMap.put("settingForServer", settingMap);
        resultMap.put("settingForParentServer", settingMapForParent);
        logAfter(logger);

        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
    }

    /**
     * 根据主机厂的主键ID更新子服务商的picture_num
     *
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/banner/updateChildrenServerPictureNumByPId")
    public ResponseBean updateChildrenServerPictureNumByPId(@RequestBody Map<String,Object> paraMap, HttpServletRequest request) throws MyException {
        logBefore(logger, "轮播图-根据主机厂的主键ID更新子服务商的picture_num");
        boolean result = appManagementService.updateChildrenServerPictureNumByPId(paraMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", result);
    }

    @PostMapping({"/banner/uploadBannerImg"})
    public Object uploadBannerImg(String s_id, Integer index, MultipartFile[] file, HttpServletRequest request) {
        logBefore(logger, "轮播图-上传轮播图图片");
        List<UploadResult> list = new ArrayList<>();
        try {
            for(MultipartFile fil : file) {
                list.add(UploadFile.uploadImg(fil, "upload/banner/" + s_id, null, null));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject resultObj = new JSONObject();
        resultObj.put("code", Constants.CODE_SUCCESS);
        if (index != null) {
            resultObj.put("message", index);
        } else {
            resultObj.put("message", "操作成功");
        }
        resultObj.put("data", list);
        logAfter(logger);
        return resultObj;
    }

    /**
     * 根据类型和序号更新轮播图片信息
     *
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/banner/updateOrAddPictureDetail")
    public ResponseBean updateOrAddPictureDetail(@RequestBody Map<String,Object> reqMap, HttpServletRequest request) throws MyException {
        logBefore(logger, "轮播图-新建或更新轮播图信息");
        reqMap.put("update_user", this.getCurrentUser(request).getId());
        boolean result = false;
        String id = reqMap.get("id").toString();
        if(!id.equals("")) { // ID不为空，则表示需要更新
            result = appManagementService.updatePictureDetail(reqMap);
        } else {    // 新增
            result = appManagementService.addPictureDetail(reqMap);
        }
        logAfter(logger);
        if(!result) {
            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", result);
        }
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", result);
    }

    /**
     * 获取主机厂、子服务商或服务商的上传的轮播图列表
     *
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/banner/getRotationChartDataListForServer")
    public ResponseBean getRotationChartDataListForServer(@RequestBody Map<String,Object> reqMap, HttpServletRequest request) throws MyException {
        logBefore(logger, "轮播图-获取主机厂、子服务商或服务商的上传的轮播图列表");
        reqMap.put("type", "0");
        List<Map<String, Object>> listForServer = appManagementService.getRotationChartDataListForServer(reqMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", listForServer);
    }

    /**
     * App首页轮播图展示(根据游客、登陆者动态拼接5张图的轮播)
     *
     * @param request
     * @return
     * @throws MyException
     */
    @PostMapping("/banner/getRotationChartDataListForIndex")
    public ResponseBean getRotationChartDataListForIndex(@RequestBody Map<String,Object> reqMap, HttpServletRequest request) throws MyException {
        logBefore(logger, "轮播图-App首页获取轮播图列表、中部广告图个人中心的广告图");
        Map<String, Object> resultMap = new HashMap();
        List<Map<String, Object>> indexList, indexMiddlePicture, personalCenterPicture;
        indexList = appManagementService.getRotationChartDataList(reqMap);
        reqMap.put("s_id", "0");    // 首页中部未开放给服务商，故选取s_id为0的首页中部图片和个人中心的图片
        reqMap.put("limit", 1);
        reqMap.put("type", "1");
        indexMiddlePicture = appManagementService.getRotationChartDataListForServer(reqMap);
        reqMap.put("type", "2");
        personalCenterPicture = appManagementService.getRotationChartDataListForServer(reqMap);
        resultMap.put("indexList", indexList);
        resultMap.put("indexMiddlePicture", indexMiddlePicture);
        resultMap.put("personalCenterPicture", personalCenterPicture);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
    }
}
